package com.general.framework.thread;

import java.util.concurrent.atomic.AtomicReference;

public class AtomicReferenceMain {
    // 声明一个AtomicReference，封装Demo对象的
    private static AtomicReference reference = new AtomicReference(new Demo());

    // 将value1、value2、value3封装为Demo对象的属性
    public static class Demo {
        public int value1 = 0;
        public int value2 = 0;
        public int value3 = 0;
    }

    // 创建线程累专门执行对象的更新
    public static class ReferenceThread extends Thread {
        @Override
        public void run() {
            for (int i = 0; i < 5000; i++) {
                Demo expected;
                Demo update;
                // 直到CAS更新操作成功才退出
                do {
                    expected = (Demo) reference.get();
                    update = new Demo();
                    update.value1 = expected.value1 + 1;
                    update.value2 = expected.value2 + 1;
                    update.value3 = expected.value2 + 1;
                } while (!reference.compareAndSet(expected, update));

                // 获取CAS之后的最新对象
                Demo curDemo = (Demo) reference.get();
                // 如果value1、value2、value3中有任意一个不相等，打印报错
                if (curDemo.value1 != curDemo.value2 || curDemo.value2 != curDemo.value3 || curDemo.value1 != curDemo.value3) {
                    System.out.println("不好意思，出错了！！！！！！");
                }

            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        // 创建两个线程，并发的操作，验证并发操作的原子性
        ReferenceThread thread1 = new ReferenceThread();
        ReferenceThread thread2 = new ReferenceThread();

        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();

        System.out.println("运行结束了......");
    }
}